<template>
  <div class="setting-content inside-comment">
    <h2 class="setting-header">
      <strong>留言设置</strong>
    </h2>
    <el-button v-permission="['build:template:content:add']" type="primary" @click="addForm">新建留言</el-button>
    <div class="form-list">
      <div class="form-item" v-for="item in applicationForm" :key="item.id">
        <div class="item-row item-name"><span>名称：</span>{{ item.name }}</div>
        <div class="item-row"><span>说明：</span>{{ item.description }}</div>
        <div class="item-row"><span>绑定审核流：</span>
          <el-select v-model="item.procdefId" placeholder="选择审核流" style="width: 240px" disabled>
            <el-option v-for="item in processList" :key="item.id" :label="item.name" :value="item.processDefinitionId" />
          </el-select>
        </div>
        <div class="item-row" v-if="item.classifyFlow.length > 0">
          <p>分类是否需要单独审核：<el-switch v-model="item.isClassifyFlow" disabled/></p>
        </div>
        <div class="item-row" v-if="item.isClassifyFlow">
          <span>设置分类审核流：</span>
          <el-radio-group class="flow-radio br" v-model="item.classifyFlow" disabled>
            <el-radio v-for="option in item.classifyFlow" :key="option.value" :label="option.value">
              <span class="radio-label">{{option.label}}</span>
              <el-select v-model="option.procdefId" placeholder="选择审核流" style="width: 120px" disabled>
                <el-option v-for="item in processList" :key="item.id" :label="item.name" :value="item.processDefinitionId" />
              </el-select>
            </el-radio>
          </el-radio-group>
        </div>
        <div class="item-row"><span>用户填写内容：</span></div>
        <div class="form-box card">
          <FormRenderer
            :fields="item.content"
            :model-value="{}"
            disabled
            label-width="100px"
          />
        </div>
        <div class="button-container">
          <el-button @click="deleteForm(item)">删除</el-button>
          <el-button @click="showForm(item)">编辑</el-button>
        </div>
      </div>
      
    </div>

    <!-- 留言设计对话框 -->
    <el-dialog
      v-model="formVisible"
      :title="formTitle"
      width="750px"
      append-to-body
    >
      <el-form :model="commentData" :rules="formRules" label-width="115px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="commentData.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="说明" prop="description">
          <el-input v-model="commentData.description" placeholder="请输入说明" />
        </el-form-item>
        <!-- <el-form-item label="审核流" prop="procdefId">
          <el-input v-model="commentData.procdefId" placeholder="请选择审核流" />
        </el-form-item> -->
        <el-form-item label="审核流" prop="procdefId">
          <!-- <el-tree-select v-model="commentData.procdefId" placeholder="选择栏目" :data="allCategory"
            :props="selectProps" default-expand-all check-strictly style="width: 180px"  /> -->
          <el-select v-model="commentData.procdefId" placeholder="选择审核流" style="width: 255px" >
            <el-option v-for="item in processList" :key="item.id" :label="item.name" :value="item.processDefinitionId" />
          </el-select>
          <div v-if="commentData.classifyFlow.length > 0" class="classify-flow">
            <p>分类是否需要单独审核<el-switch v-model="commentData.isClassifyFlow" @change="initClassifyFlow"/></p>
          </div>
        </el-form-item>
        <el-form-item v-if="commentData.isClassifyFlow" label="设置分类审核流" prop="classifyFlow">
          <el-radio-group class="flow-radio" v-model="commentData.classifyFlow">
            <el-radio v-for="option in commentData.classifyFlow" :key="option.value" :label="option.value">
              <span class="radio-label">{{option.label}}</span>
              <!-- <el-tree-select v-model="option.catId" placeholder="选择栏目" :data="allCategory"
                  :props="selectProps" default-expand-all check-strictly style="width: 180px" /> -->
              <el-select v-model="option.procdefId" placeholder="选择审核流">
                <el-option v-for="item in processList" :key="item.id" :label="item.name" :value="item.processDefinitionId" />
              </el-select>
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <p class="user-item">用户填写内容</p>
        <div class="form-box no-margin-bottom">
          <FormRenderer
            :fields="commentData.content"
            :model-value="{}"
            disabled
            label-width="100px"
          />
          <div class="button-container">
            <el-button @click="showFormDesigner(commentData.content)">编辑</el-button>
          </div>
        </div>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="formVisible = false">取消</el-button>
          <el-button type="primary" @click="saveForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 表单设计对话框 -->
    <el-dialog
      v-model="formDesignerVisible"
      title="留言表单设计"
      width="1100px"
      append-to-body
    >
      <FormDesigner ref="formDesignerRef" v-model="formData"/>
      <div class="tips">请确保留言表单至少有标题和留言，分类改动会出现数据丢失</div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="formDesignerVisible = false">取消</el-button>
          <el-button type="primary" @click="saveFormDesigne">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, reactive } from "vue";
import { 
  selectListCommentForm,
  insertCommentForm,
  updateCommentForm,
  deleteCommentForm
 } from "@/api/form";
import FormDesigner from "../components/FormDesigner";
import FormRenderer from "../components/FormRenderer";
import { ElMessage, ElMessageBox } from "element-plus";
import { getProcessList } from "@/api/workflow"

const formTitle = ref("");
const formVisible = ref(false);
const formDesignerVisible = ref(false);
const applicationForm = ref([]);
const formDesignerRef = ref(null);
const formData = ref([]);

const props = defineProps({
  defaultCommentData: {
    type: Object,
    default: () => {
      return {
        procdefId: '',
        content: [],
        description: "",
        id: 0,
        name: "",
        isClassifyFlow: false,
        classifyFlow: []
      };
    },
  },
});

let commentData = ref(JSON.parse(JSON.stringify(props.defaultCommentData)));

// 获取内已发布工作流
const processList = ref([])
const _getProcessList = () => {
  getProcessList().then(res => {
    processList.value = res.data
  })
}
_getProcessList()

//获取留言表单
const getCommentForm = async () => {
  const res = await selectListCommentForm();
  if (res.code === 20000) {
    applicationForm.value = res.data;
  }
};
getCommentForm()

//新增留言
const addForm = () => {
  formTitle.value = "新增留言";
  formVisible.value = true;
  commentData.value = JSON.parse(JSON.stringify(props.defaultCommentData))
  commentData.value.content = [
    {
        "options": [],
        "name": "biao_ti_cm52",
        "label": "标题",
        "id": "1741073423226",
        "type": "input",
        "required": "true"
    },
    {
        "options": [],
        "name": "liu_yan_x3u9",
        "label": "留言",
        "id": "1741073433507",
        "type": "textarea",
        "required": "true"
    }
]
  // console.log("defaultCommentData",JSON.parse(JSON.stringify(props.defaultCommentData)));
  // console.log("commentData",commentData.value);
};
const addCommentForm = async () => {
  try {
    const res = await insertCommentForm(commentData.value);
    if (res.code === 20000) {
      getCommentForm();
      ElMessage.success("新增留言成功");
    }
  } catch (error) {
    ElMessage.error("新增留言失败");
  }
}

//保存留言
const saveForm = () => {
  // 表单标题校验
  if (!commentData.value.name.trim()) {
    ElMessage({
      showClose: true,
      message: `名称不能为空，请填写`,
      type: 'warning'
    })
    return false
  }
  if (!commentData.value.description.trim()) {
    ElMessage({
      showClose: true,
      message: `说明不能为空，请填写`,
      type: 'warning'
    })
    return false
  }
  if (commentData.value.content.length < 1) {
    ElMessage({
      showClose: true,
      message: `留言表单不能为空，请填写`,
      type: 'warning'
    })
    return false
  }
  // if(commentData.value.isClassifyFlow == false){
  //   commentData.value.classifyFlow = []
  // }
  if(commentData.value.id == 0){
    addCommentForm()
  } else{
    updateCommentFormData();
  }
  formVisible.value = false;
};

//表单校验
const formRules = reactive({
  name: [
    { required: true, message: '名称不能为空', trigger: 'blur' }
  ],
  description : [
    { required: true, message: '说明不能为空', trigger: 'blur' }
  ],
  procdefId : [
    { required: true, message: '请选择留言对应审核流', trigger: 'blur' }
  ]
});

//删除留言
const deleteForm = async (item) => {
  ElMessageBox.confirm("是否删除该留言？", "删除确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      const res = await deleteCommentForm({id:item.id});
      if (res.code === 20000) {
        ElMessage.success("删除留言成功");
        getCommentForm();
      }
    } catch (error) {
      ElMessage.error("删除留言失败");
    }
  })
};

//设置分类单独审核，默认使用留言审核流
const initClassifyFlow = () => {
  if(commentData.value.isClassifyFlow == true){
    commentData.value.classifyFlow.forEach(item => {
      item.procdefId = commentData.value.procdefId
    });
    console.log("commentData.value",commentData.value);
    
  }
}

//保存留言表单
const saveFormDesigne = () => {
  if (formDesignerRef.value) {
    // 调用子组件暴露的 save 方法
    formDesignerRef.value.save();
  } 
  //更新留言表单
  console.log("formData.value",formData.value);
  formData.value.forEach(element => {
    if(element.type == "classify"){
      commentData.value.classifyFlow = element.options;
      commentData.value.classifyFlow.forEach(element => {
        element.procdefId = ''
      });
    }
  });
  commentData.value.content = formData.value
  // updateCommentFormData()
  formDesignerVisible.value = false;
};

//留言编辑对话框显示
const showForm = (item) => {
  formTitle.value = "编辑留言"
  formVisible.value = true;
  commentData.value = item;
  console.log("commentData",commentData.value);
};

//表单编辑对话框显示
const showFormDesigner = (item) => {
  formDesignerVisible.value = true;
  formData.value = item;
};

//更新留言表单
const updateCommentFormData = async () => {
  try {
    const res = await updateCommentForm(commentData.value);
    if (res.code === 20000) {
      getCommentForm();
      ElMessage.success("编辑留言成功");
    }
  } catch (error) {
    ElMessage.error("编辑留言失败");
  }
};

</script>

<style lang="scss" scoped>
.manage-header {
  margin-top: 10px;
}
.form-list {
  display: flex;
  flex-wrap: wrap;
  margin-top: 10px;
  .form-item {
    width: 450px;
    min-height: 200px;
    padding: $padding-medium;
    border-radius: 5px;
    border: 1px solid $borderColor;
    margin-right: 20px;
    margin-bottom: 20px;
    color:$black_2;
    .item-name{
      font-size: 16px;
    }
    .item-row {
      font-size: 14px;
      margin-bottom: 10px;
      &.item-name{
        font-size: 18px;
        font-weight: bold;
      }
      span{
        color: $black;
      }
    }
    .button-container{
      display: flex;
      justify-content: end;
      button {
        margin-left: 10px;
      }
    }
  }
}
.classify-flow{
  margin-left: 20px;
  .el-switch{
    margin-left: 10px;
  }
}
.flow-radio{
  &.br{
    margin-top: 10px;
  }
  .el-radio{
    margin-right: 30px;
    margin-bottom: 10px;
    .radio-label{
      /* margin-right: 10px; */
    }
    .el-select{
      margin-left: 10px;
    }
    &:last-child{
      margin-right: 0;
    }
  }
} 
.form-box{
  padding: 15px 15px 0;
  border: 1px solid $borderColor;
  border-radius: 4px;
  margin-bottom: 10px;
  &.no-margin-bottom{
    margin-bottom: 0;
  }
  .button-container{
    display: flex;
    justify-content: end;
    margin-bottom: 15px;
  }
  &.card{
    ::v-deep .el-radio-group{
      position: relative;
      
    }
  }
  
}
.user-item{
  color: var(--el-text-color-regular);
  margin-bottom: 15px;
}
.tips{
  font-size: 12px;
  margin-top: 10px;
  color: $mainColor;
}
</style>
